<script setup lang="ts">
  import { page, push, remove } from '@/api/timeline.ts'
  import { TimelinePageParam, Timeline } from '@/types'
  import TableCustom from '@/components/common/TableCustom.vue'
  import TableSearch from '@/components/common/TableSearch.vue'
  import TimelineEdit from '@/views/timeline/TimelineEdit.vue'
  import { FormOption, TableColumns } from '@/types/form-option.ts'
  import {
    CirclePlusFilled,
    Delete,
    Edit,
    Finished,
    List,
    Operation,
  } from '@element-plus/icons-vue'
  import { ElMessage, ElTimeline, ElTimelineItem } from 'element-plus'
  import { onMounted, reactive, ref } from 'vue'

  const formatDate = (dateString: string): string => {
    if (!dateString) return ''
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  const searchOpt = ref<FormOption[]>([{ type: 'input', label: '关键字：', prop: 'keyword' }])

  // 表格字段配置
  const columns = ref<TableColumns[]>([
    { type: 'index', prop: '', label: '序号', width: 55, align: 'center' },
    { prop: 'title', label: '标题' },
    { prop: 'content', label: '内容' },
    { prop: 'date', label: '日期', width: 180, slot: 'date' },
    { prop: 'status', label: '状态', width: 100 },
    { prop: 'operator', label: '操作', width: 300 },
  ])

  const param = reactive<TimelinePageParam>({
    keyword: '',
    pageNum: 1,
    pageSize: 10,
  })

  const visible = ref(false)
  const isEdit = ref(false)
  const rowData = ref<Timeline | undefined>()
  const tableData = ref<Timeline[]>([])
  const total = ref(0)

  const viewMode = ref<'table' | 'timeline'>('table')

  const toggleViewMode = () => {
    viewMode.value = viewMode.value === 'table' ? 'timeline' : 'table'
  }

  //搜索方法
  const handleSearch = () => {
    changePage(1)
  }

  const handleAdd = () => {
    rowData.value = undefined
    visible.value = true
    isEdit.value = false
  }

  const handleEdit = (row: Timeline) => {
    rowData.value = { ...row }
    visible.value = true
    isEdit.value = true
  }

  const handleChangeStatus = async (row: Timeline) => {
    await push({ id: row.id, status: row.status === 1 ? 0 : 1 })
    ElMessage.success(row.status === 1 ? '已下架' : '已发布')
    await getData()
  }

  const handleDelete = async (row: Timeline) => {
    await remove({ id: row.id })
    ElMessage.success('删除成功')
    await getData()
  }

  const changePage = (val: number) => {
    param.pageNum = val
    getData()
  }

  //查询分页
  const getData = async () => {
    try {
      const data = await page(param)
      tableData.value = data.records
      total.value = data.total
    } catch (error) {
      ElMessage.error('获取数据失败')
      console.error(error)
    }
  }

  const closeDialog = (refresh: boolean = false) => {
    visible.value = false
    if (refresh) {
      getData()
    }
  }

  onMounted(() => {
    getData()
  })
</script>

<template>
  <div>
    <!--  搜索栏  -->
    <TableSearch :query="param" :options="searchOpt" :search="handleSearch" />
    <div class="container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <div>
          <el-button type="warning" :icon="CirclePlusFilled" @click="handleAdd">新增</el-button>
        </div>
        <div>
          <el-button type="primary" @click="toggleViewMode">
            <el-icon class="mr-5">
              <component :is="viewMode === 'table' ? Operation : List" />
            </el-icon>
            {{ viewMode === 'table' ? '历程视图' : '表格视图' }}
          </el-button>
        </div>
      </div>

      <!-- Wrapper for content with min-height -->
      <div class="content-area" style="min-height: 400px">
        <TableCustom
          v-if="viewMode === 'table'"
          :columns="columns"
          :table-data="tableData"
          :total="total"
          :current-page="param.pageNum"
          :page-size="param.pageSize"
          :change-page="changePage"
          table-min-height="450px"
        >
          <template #content="{ row }">
            <el-tooltip effect="light">
              <template #content>
                <span style="max-width: 500px">{{ row.content }}</span>
              </template>
              <span>{{ row.content }}</span>
            </el-tooltip>
          </template>
          <template #date="{ row }">
            {{ formatDate(row.date) }}
          </template>
          <template #status="{ row }">
            <el-tag v-if="row.status == 1" type="success">已发布</el-tag>
            <el-tag v-else type="info">未发布</el-tag>
          </template>
          <template #operator="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              type="warning"
              size="small"
              :icon="Finished"
              @click="handleChangeStatus(row)"
            >
              {{ row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </TableCustom>

        <div v-else class="timeline-view-container">
          <ElTimeline v-if="tableData.length > 0">
            <ElTimelineItem
              v-for="item in tableData"
              :key="item.id"
              :timestamp="formatDate(item.date)"
              placement="top"
            >
              <el-card>
                <h4>{{ item.title }}</h4>
                <p>{{ item.content }}</p>
                <div>
                  <el-tag size="small" :type="item.status === 1 ? 'success' : 'info'" class="mr-10">
                    {{ item.status === 1 ? '已发布' : '未发布' }}
                  </el-tag>
                  <el-button
                    type="primary"
                    size="small"
                    :icon="Edit"
                    class="mr-5"
                    @click="handleEdit(item)"
                  >
                    编辑
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    :icon="Finished"
                    class="mr-5"
                    @click="handleChangeStatus(item)"
                  >
                    {{ item.status === 1 ? '下架' : '发布' }}
                  </el-button>
                  <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(item)">
                    删除
                  </el-button>
                </div>
              </el-card>
            </ElTimelineItem>
          </ElTimeline>
          <el-empty v-else description="暂无历程数据" />
        </div>
      </div>

      <!-- Pagination: Show only for timeline view if TableCustom has its own -->
      <div v-if="total > 0 && viewMode === 'timeline'" class="pagination-container">
        <el-pagination
          v-model:current-page="param.pageNum"
          :page-size="param.pageSize"
          :total="total"
          layout="prev, pager, next, jumper, total"
          background
          @current-change="changePage"
        />
      </div>
    </div>

    <el-dialog
      v-model="visible"
      :title="isEdit ? '编辑历程' : '新增历程'"
      destroy-on-close
      :show-close="false"
      width="50%"
    >
      <template #header>
        <div class="dialog-header">
          <span style="font-size: 16px; font-weight: bold">
            {{ isEdit ? '编辑历程' : '新增历程' }}
          </span>
          <el-button type="danger" style="float: right" @click="closeDialog(false)">关闭</el-button>
        </div>
      </template>
      <TimelineEdit :data="rowData" @close="closeDialog" />
    </el-dialog>
  </div>
</template>

<style scoped>
  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    margin-bottom: 20px;
  }

  .timeline-view-container {
    padding: 20px 0;
  }

  .mr-5 {
    margin-right: 5px;
  }

  .mr-10 {
    margin-right: 10px;
  }
</style>
